<template>
  <!--其它配置-->
  <div class="main-container">
    <el-card class="box-card !border-none" shadow="never">
      <!-- 勾调一杯乐容量规格 -->
      <div class="flex justify-between items-center">
        <span class="text-page-title">{{ t("bottleCapacity") }}</span>
      </div>
      <div class="flex justify-between items-center mt-[20px]">
        <span class="text-page-title">{{ t("happyCup") }}</span>
      </div>
      <div class="mt-[20px]">
        <el-tag
          v-for="(tag, index) in capacityData.formData.alcohol_sku"
          :key="index"
          type="primary"
          size="large"
          round
        >
          <div class="capacity">
            <span>{{ t("capacity") }} ：{{ tag?.sku || 0 }}ml</span>
            <span class="ml-[10px]">
              {{ t("deliveryMoney") }} ：{{ tag?.delivery_money || 0 }}元
            </span>
          </div>
          <el-button
            type="primary"
            :icon="Edit"
            plain
            circle
            size="small"
            round
            @click="editCapacityEvent(index)"
          />
          <el-button
            type="primary"
            :icon="Close"
            plain
            circle
            size="small"
            round
            @click="delCapacityEvent(index)"
          />
        </el-tag>
        <el-button type="primary" round @click="addCapacityEvent()">
          {{ t("addCapacity") }}
        </el-button>
        <el-empty
          v-if="!capacityData.formData.alcohol_sku.length"
          :description="t('emptyData')"
          :image-size="70"
        />
      </div>
      <!-- 私人定制乐容量规格 -->
      <div class="flex justify-between items-center mt-[10px]">
        <span class="text-page-title">{{ t("customized") }}</span>
      </div>
      <el-form
        ref="capacityformRef"
        v-loading="capacityLoading"
        :model="capacityData.formData"
        :rules="capacityFormRules"
        label-width="90px"
        inline
        class="page-form mt-[20px]"
      >
        <el-form-item :label="t('capacity')" prop="bartender_sku.sku">
          <el-input
            v-model.trim="capacityData.formData.bartender_sku.sku"
            :placeholder="t('capacityPlaceholder')"
            type="number"
            clearable
            class="input-width"
          >
            <template #suffix>ml</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="t('deliveryMoney')" prop="bartender_sku.delivery_money">
          <el-input
            v-model.trim="capacityData.formData.bartender_sku.delivery_money"
            :placeholder="t('deliveryMoneyPlaceholder')"
            type="number"
            clearable
            class="input-width"
          >
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="capacityLoading"
            @click="capacityConfirm(capacityformRef)"
          >
            {{ t("confirm") }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 杯价格设置 -->
    <el-card class="box-card !border-none mt-[20px]" shadow="never">
      <div class="flex justify-between items-center">
        <span class="text-page-title">{{ t("cupPriceSetting") }}</span>
      </div>
      <el-form
        ref="cupFormRef"
        v-loading="cupLoading"
        :model="capacityData.formData"
        :rules="cupFormRules"
        label-width="90px"
        inline
        class="page-form mt-[20px]"
      >
        <el-form-item :label="t('price')" prop="cup_price">
          <el-input
            v-model.trim="capacityData.formData.cup_price"
            :placeholder="t('pricePlaceholder')"
            type="number"
            clearable
            maxlength="255"
            class="input-width"
          >
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="cupLoading" @click="cupConfirm(cupFormRef)">
            {{ t("confirm") }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 预付金设置 -->
    <el-card class="box-card !border-none mt-[20px]" shadow="never">
      <div class="flex justify-between items-center">
        <span class="text-page-title">{{ t("downPayment") }}</span>
      </div>
      <el-form
        ref="payFormRef"
        v-loading="payLoading"
        :model="capacityData.formData"
        :rules="payFormRules"
        label-width="90px"
        inline
        class="page-form mt-[20px]"
      >
        <el-form-item :label="t('price')" prop="bartender_prepay">
          <el-input
            v-model.trim="capacityData.formData.bartender_prepay"
            :placeholder="t('pricePlaceholder')"
            type="number"
            clearable
            maxlength="255"
            class="input-width"
          >
            <template #suffix>元</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="payLoading" @click="payConfirm(payFormRef)">
            {{ t("confirm") }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <edit-capacity ref="editCapacityDialog" @complete="loadOtherConfig()" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { t } from "@/lang";
import { getOtherConfig, saveOtherConfig } from "@/app/api/alcohol";
import { ElMessageBox, ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { Edit, Close } from "@element-plus/icons-vue";
import editCapacity from "@/app/views/alcohol/components/edit-capacity.vue";

const capacityData = reactive({
  formData: {
    type: "alcohol_config",
    alcohol_sku: [],
    bartender_sku: {
      sku: null,
      delivery_money: null,
    },
    cup_price: null,
    bartender_prepay: null,
  },
});
const editCapacityDialog: Record<string, any> | null = ref(null);

// 专家私人定制
const capacityformRef = ref<FormInstance>();
const capacityLoading = ref(false);
const capacityFormRules = reactive({
  "bartender_sku.sku": [
    { required: true, message: t("capacityPlaceholder"), trigger: "blur" },
  ],
  "bartender_sku.delivery_money": [
    { required: true, message: t("deliveryMoneyPlaceholder"), trigger: "blur" },
  ],
});
// 分杯装
const cupFormRef = ref<FormInstance>();
const cupLoading = ref(false);
const cupFormRules = reactive({
  cup_price: [{ required: true, message: t("pricePlaceholder"), trigger: "blur" }],
});
// 预付款
const payFormRef = ref<FormInstance>();
const payLoading = ref(false);
const payFormRules = reactive({
  bartender_prepay: [{ required: true, message: t("pricePlaceholder"), trigger: "blur" }],
});

onMounted(() => {
  loadOtherConfig();
});

/**
 * 获取其它配置详情
 */
const loadOtherConfig = () => {
  getOtherConfig().then((res) => {
    let detail = res.data;
    detail.alcohol_sku = JSON.parse(detail.alcohol_sku);
    detail.bartender_sku = JSON.parse(detail.bartender_sku);
    capacityData.formData = detail;
  });
};

/**
 * 编辑容量规格
 * @param data
 */
const editCapacityEvent = (index: number) => {
  const data = capacityData.formData.alcohol_sku;
  editCapacityDialog.value.setFormData({
    index,
    data,
  });
  editCapacityDialog.value.showDialog = true;
};

/**
 * 添加容量规格
 */
const addCapacityEvent = () => {
  const data = capacityData.formData.alcohol_sku || [];
  editCapacityDialog.value.setFormData({
    index: -1,
    data,
  });
  editCapacityDialog.value.showDialog = true;
};

/**
 * 删除容量规格
 * @param data
 */
const delCapacityEvent = (index: number) => {
  ElMessageBox.confirm(t("confirmDelete"), t("deleteTips"), {
    confirmButtonText: t("confirm"),
    cancelButtonText: t("cancel"),
    type: "warning",
  })
    .then(() => {
      capacityData.formData.alcohol_sku.splice(index, 1);
      submitForm("alcohol_sku");
    })
    .catch(() => {});
};

// 保存专家私人定制容量规格
const capacityConfirm = async (formEl: FormInstance | undefined) => {
  if (capacityLoading.value || !formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      capacityLoading.value = true;
      await submitForm("bartender_sku");
      capacityLoading.value = false;
    }
  });
};

// 保存分杯装价格
const cupConfirm = async (formEl: FormInstance | undefined) => {
  if (cupLoading.value || !formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      cupLoading.value = true;
      await submitForm("cup_price");
      cupLoading.value = false;
    }
  });
};

// 保存预付金
const payConfirm = async (formEl: FormInstance | undefined) => {
  if (payLoading.value || !formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      payLoading.value = true;
      await submitForm("bartender_prepay");
      payLoading.value = false;
    }
  });
};

// 保存其它配置
const submitForm = (field: string) => {
  return new Promise((resolve) => {
    let data = {
      [field]: capacityData.formData[field],
    };
    if (field == "alcohol_sku" || field == "bartender_sku") {
      data[field] = JSON.stringify(data[field]);
    }
    saveOtherConfig(data)
      .then(() => {
        loadOtherConfig();
        ElMessage.success(t("saveSuccess"));
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};
</script>

<style lang="scss" scoped>
.capacity {
  display: inline-block;
  margin-right: 10px;
  vertical-align: middle;
}
.el-button + .el-button {
  margin-left: 0;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  vertical-align: top;
}
</style>
